<template>
  <div class="AcTitle">用户列表</div>
  <el-table :data="pageData.userlist.slice((pageData.current-1)*pageData.pagesize,pageData.current*pageData.pagesize)" style="width: 100%">
    <el-table-column label="序号" > <template  #default="scope"><span>{{(pageData.current - 1) * pageData.pagesize + scope.$index + 1}}</span></template></el-table-column>
    <el-table-column label="ID" prop="uid" />
    <el-table-column label="账号" prop="account" />
    <el-table-column label="密码"  >
      <template #default="scope">
        <el-input
        v-model="scope.row.password"
        type="password"
        placeholder="Please input password"
        show-password/>
      </template>
    </el-table-column>
    <el-table-column label="姓名" prop="name" />  
    <el-table-column label="电话号码" prop="userphone" />
    <el-table-column align="right">
      <template #header>
        <el-input v-model="usersearch" size="small" placeholder="姓名或账号进行搜索..."/> 
         <el-button size="small" @click="handleSearch()"
          ><el-icon><search /></el-icon
        ></el-button>
        <el-button size="small" @click="handleRef()"
          ><el-icon><refresh /></el-icon
        ></el-button>
        <el-button size="small" @click="handleAdd()"
          ><el-icon><plus /></el-icon
        ></el-button>
      </template>

      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
          ><el-icon><edit /></el-icon
        ></el-button>
        <el-button
          size="small"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)"
          ><el-icon><delete /></el-icon
        ></el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--编辑面版 -->
  <el-dialog
    v-model="dialogFormVisible"
    title="编辑用户信息"
  >
    <el-form :model="EditdialogData">
      <el-form-item label="ID" label-width="200px" class="elstyle">
        <el-input disabled v-model="EditdialogData.uid" />
      </el-form-item>
      <el-form-item label="账号" class="elstyle" label-width="200px">
        <el-input disabled v-model="EditdialogData.account" />
      </el-form-item>
      <el-form-item label="密码" class="elstyle" label-width="200px">
        <el-input v-model="EditdialogData.password" />
      </el-form-item>
      <el-form-item label="用户名" class="elstyle" label-width="200px">
        <el-input v-model="EditdialogData.name" />
      </el-form-item>
      <el-form-item label="电话号码" class="elstyle" label-width="200px">
        <el-input v-model="EditdialogData.userphone" type="email" />
      </el-form-item>
        <el-form-item   class="elstyle" label-width="180px">
        <el-radio-group v-model="EditdialogData.role" size="large">
          <el-radio :label="1" >用户管理员</el-radio>
          <el-radio :label="2" >影院管理员</el-radio>
          <el-radio :label="3">用户</el-radio>
    </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateUserInfo">保存</el-button>
      </span>
    </template>
  </el-dialog>

   <!--添加用户面版 -->
  <el-dialog
    v-model="dialogFormVisible1"
    title="添加用户"
  >
    <el-form :model="AdduserdialogData" :rules="rules">
      <el-form-item label="账号" class="elstyle" label-width="200px">
        <el-input v-model="AdduserdialogData.account"/>
      </el-form-item>
      <el-form-item label="密码" class="elstyle" label-width="200px">
        <el-input   v-model="AdduserdialogData.password"/>
      </el-form-item>
      <el-form-item label="用户名" class="elstyle" label-width="200px">
        <el-input   v-model="AdduserdialogData.name"/>
      </el-form-item>
      <el-form-item label="电话号码" class="elstyle" label-width="200px">
        <el-input   v-model="AdduserdialogData.userphone"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取消</el-button>
        <el-button type="primary" @click="addUserInfo">添加</el-button>
      </span>
    </template>
  </el-dialog>
  <!--分页 -->
    <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="pageData.current"
    layout="prev, pager,next,total,jumper"
    :total="pageData.total"
    :page-size="pageData.pagesize"
  />

</template>

<script lang="ts">
import { computed, onMounted, reactive, ref, inject } from "vue";
import { Delete, Refresh, Edit, Plus, Search} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import {
  postUserDeleteAPI,
  postRegisterAPI,
  postSelectAPI,
  getUserSearchAPI,
} from "../../api/userinfo";
import { useStore } from "vuex";
export default {
  components: { Delete, Refresh, Edit, Plus,Search },

  setup() {
    interface User {
      uid?: number;
      account: string;
      password: string;
      name: string;
      userphone: string;
      avatar:string;
      role:number;
    }
    onMounted(() => {
      handleRefs();
    });
    const store=useStore();
    const usersearch = ref("");
    const reload=inject("reload",() => {})
    const AdduserdialogData=reactive({
      account: "",
      password: "",
      name: "",
      userphone: "",
      avatar:""
    })
    let EditdialogData = reactive({
      uid: 1,
      account: "",
      password: "",
      name: "",
      userphone: "",
      avatar:"",
      role:3
    });
         /**分页 */
    const pageData=reactive({
       current:1,//当前页
       pagesize:12,// 当前页显示多少条
       userlist:ref([]),
       total:0  //总数据
     })
    /**是否打开编辑框：默认false */
    let dialogFormVisible = ref(false);
      /**是否打开添加用户信息框：默认false */
    let dialogFormVisible1 = ref(false);
    /**编辑框 */
    const handleEdit = (index: number, row: User) => {
      dialogFormVisible.value = true;
      let key: keyof User;
      for (key in row) {
        EditdialogData[key] = row[key] as never;
      }
    };
    /**删除用户 */
    const handleDelete = async (index: number, row: User) => {
      console.log(row);
      store.dispatch("SET_DELETEINFO",{uid:row.uid}).then(()=>{
        ElMessage.success("删除成功");
        reload();
      })

    };
    /**添加用户 */
    const handleAdd = () => {
      dialogFormVisible1.value=true;
    };
    /**界面刷新 */
    const handleRefs = async () => {
      await postSelectAPI()
        .then((res) => {
          res.data.forEach((element: never) => {
             pageData.userlist.push(element)  
          });
           pageData.total=pageData.userlist.length;
        })
        .catch((err: any) => {
          ElMessage.error("加载失败");
        });
    };
    /**按钮刷新 */
    const handleRef = async () => {
       reload();
    };
    /**更新信息 */
    const updateUserInfo =  () => {
      dialogFormVisible.value = false;
      console.log(EditdialogData);
      store.dispatch("SET_UPDATEINFO",EditdialogData).then(()=>{
        ElMessage.success("更新成功");
      })
      reload();
    };
    /**按条件搜索 */
    const handleSearch=async()=>{
      await getUserSearchAPI({
        usersearch :usersearch.value
      }) .then((res) => {
        pageData.userlist=[]
          if(res.data.length==0){
         ElMessage.error("用户不存在或者查询条件错误");
          }
          else{
              res.data.forEach((element: never) => {
             pageData.userlist.push(element)
          });
          pageData.total=pageData.userlist.length;
          ElMessage({
            message: "查询成功",
            type: "success",
            center: true,
            grouping: true,
          });
          usersearch.value="";
          }
        })
        .catch((err: any) => {
          ElMessage.error("查询失败");
        });
    }
    /**添加用户信息 */
    const addUserInfo= async ()=>{
        dialogFormVisible1.value = false;
        await postRegisterAPI({
        account: AdduserdialogData.account,
        password: AdduserdialogData.password,
        name: AdduserdialogData.name,
        userphone: AdduserdialogData.userphone,
        }).then((res)=>{
           ElMessage({
            message: "添加成功",
            type: "success",
            center: true,
            grouping: true,
          });
          pageData.userlist=[]
          handleRefs();
        }).catch((err: any) => {
          ElMessage.error("添加失败，请检查你的数据格式");
        });
    }
    /**注册校验规则 */
    const rules = reactive({
      Raccount: [
        { required: true, message: "账号不能为空", trigger: "blur" },
        {
          min: 5,
          max: 12,
          message: "账号长度应在5-12之间",
          trigger: "blur",
        },
      ],
      Rpassword: [
        { required: true, message: "密码不能为空", trigger: "blur" },
        { min: 6, max: 12, message: "密码长度应在6-12之间", trigger: "blur" },
      ],
      Rname: [
        { required: true, message: "用户名不能为空", trigger: "blur" },
        { min: 2, max: 7, message: "用户名长度应该在2-7之间",trigger: "blur"},
      ],
      Rphone :[{ required: true, message: "电话号码不能为空" ,trigger: "blur" },
        { min: 11, max: 11, message: "电话号码长度不正确",trigger: "blur"},
      ],
    });
    const handleSizeChange=(value:any)=>{
      pageData.pagesize=value;
      pageData.userlist=[];
      handleRefs();

    }   
    const handleCurrentChange=(value:any)=>{
      pageData.current=value;
      pageData.userlist=[];
      handleRefs();
    }
    return {
      handleEdit,
      handleDelete,
      handleAdd,
      handleRef,
      handleSearch,
      updateUserInfo,
      addUserInfo,
      dialogFormVisible,
      dialogFormVisible1,
      EditdialogData,
      AdduserdialogData,
      handleSizeChange,
      handleCurrentChange,
      pageData,
      usersearch,
      rules,
    };
  },
};
</script>
<style>
.AcTitle {
  font-size: 1.5rem;
  margin: 20px 0 10px 0;
}
.el-table .cell {
  padding: 5px 12px;
}
.elstyle input {
  width: 220px;
}
.el-pagination{
  padding: 50px 10px;
  margin-left: 35rem;
}
.el-input--small .el-input__inner {
  margin-bottom: 13px;
}
</style>
